package io.github.talelin.latticy.controller.v1;


import io.github.talelin.latticy.service.ArticleService;
import io.github.talelin.latticy.service.QueryLogService;
import io.github.talelin.latticy.vo.*;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import io.github.talelin.latticy.model.ArticleDO;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.validation.constraints.Positive;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/v1/article")
@Validated
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private QueryLogService queryLogService;

    @PostMapping("")
    public CreatedVO create() {
        return new CreatedVO();
    }

    @PutMapping("/{id}")
    public UpdatedVO update(@PathVariable @Positive(message = "{id.positive}") Integer id) {
        return new UpdatedVO();
    }

    @DeleteMapping("/{id}")
    public DeletedVO delete(@PathVariable @Positive(message = "{id.positive}") Integer id) {
        return new DeletedVO();
    }

    @GetMapping("/{id}")
    public ArticleDO get(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id) {
        return null;
    }

    @GetMapping("/search")
    public PageResponseVO<ArticleSummaryVO> search(
            @RequestParam(name = "count", required = false, defaultValue = "10")
            @Min(value = 1, message = "{page.count.min}")
            @Max(value = 30, message = "{page.count.max}") Integer count,
            @RequestParam(name = "page", required = false, defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Integer page,
            @RequestParam(name = "query", required = true)
            @Length(min = 1, message = "最小3个字，最大30个字")
                    String query
    ) throws IOException {
        if(query.length()>40) query.substring(0, 40);
        queryLogService.createLog(query);
        return this.articleService.searchES(query, page, count);
    }

    @GetMapping("/get/by/{id}")
    public ArticleVO searchById(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id
    ) throws IOException {
        return this.articleService.getArticle(id);
    }
}
